package com.simple.datax.db.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.common.logger.Logger;
import com.alibaba.dubbo.common.logger.LoggerFactory;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.simple.datax.SimpleFailMessage;
import com.simple.datax.SimpleObject;
import com.simple.datax.api.SimpleException;
import com.simple.datax.db.mybatis.client.DataxFailedMapper;
import com.simple.datax.db.mybatis.client.DataxProcingMapper;
import com.simple.datax.db.mybatis.model.DataxFailed;
import com.simple.datax.service.DBDataxFialedService;
import com.simple.datax.service.SimpleDBException;

/**
 * @Title: DBDataxFailedServiceImpl.java
 * @Package com.simple.datax.db.service.impl
 * @Description: 实现发送失败服务
 * @author Paladin Chen
 * @date 2012-12-24 下午3:12:09
 * @version V1.0
 */
@Service("dbFailService")
public class DBDataxFailedServiceImpl implements DBDataxFialedService {
	private static final Logger logger = LoggerFactory.getLogger(DBDataxFailedServiceImpl.class);

	@Autowired
	private DataxFailedMapper dfm;

	@Autowired
	private DataxProcingMapper dpm;

	@Override
	public void process(SimpleObject src) throws SimpleException {
		if (src instanceof SimpleFailMessage) {
			logger.debug("Begin to db fail proc......" + ((SimpleFailMessage) src).toLog());

			// 删除procing状态库的记录
			if (!StringUtils.isBlank(((SimpleFailMessage) src).getRecvRawMsgid())) {
				dpm.deleteByPrimaryKey(((SimpleFailMessage) src).getRecvRawMsgid());
			}

			DataxFailed df = new DataxFailed();

			// 记载信息最多为1K
			String errorInfo = ((SimpleFailMessage) src).getErrorInfo();
			if (errorInfo!=null && errorInfo.length() > 1023) {
				errorInfo = errorInfo.substring(0, 1020) + "...";
			}

			df.setErrorInfo(errorInfo);
			df.setErrorLevel(((SimpleFailMessage) src).getErrorLevel());
			df.setErrorStatus((short) 0); // 未处理，错误创建时缺省状态
			df.setErrorType(((SimpleFailMessage) src).getErrorType());
			df.setMsgFormate(((SimpleFailMessage) src).getMsgFormate());
			df.setMsgReceiver(((SimpleFailMessage) src).getMsgReceiver());
			df.setMsgType(((SimpleFailMessage) src).getMsgType());
			df.setMsgSender(((SimpleFailMessage) src).getMsgSender());
			df.setMessageid(((SimpleFailMessage) src).getMessageid());
			df.setRecvRawMsgid(((SimpleFailMessage) src).getRecvRawMsgid());
			df.setSendRawMsgid(((SimpleFailMessage) src).getSendRawMsgid());

			dfm.insertSelective(df);

			logger.debug("Finish db fail proc......" + ((SimpleFailMessage) src).toLog());
		} else {
			//logger.error("This function ONLY process SimpleFailMessage.");
			throw new SimpleDBException("The Parameter is NOT SimpleFailMessage!!");
		}

	}

}
